﻿using FireChat.Server.Database.Manager;
using FireChat.Server.Session;
using FireChat.Server.Session.Receiver;
using FireChat.Share.Command;
using FireChat.Share.Logger;
using System.Text;

namespace FireChat.Server;


/// <summary>
/// 服务端 控制台
/// </summary>
internal class ServerConsole
{
    /// <summary>
    /// 指令映射表
    /// </summary>
    private static readonly CommandMap<ServerConsole> Commands = new();

    /// <summary>
    /// 服务端 核心
    /// </summary>
    private static ServerCore ServerCore = Restart();



    /// <summary>
    /// 服务端 控制台
    /// </summary>
    public static void Main()
    {
        Console.Title = "FireChat Server";
        Commands.Start();
    }


    #region --指令区--


    [CommandToken("clr", "clear", "清屏")]
    public static void ClearScreen()
    {
        Console.Clear();
    }


    [CommandToken("restart", "重启")]
    private static ServerCore Restart()
    {
        $"正在启动服务端核心...".LogToConsole();

        try
        {
            try { ServerCore?.Close(); } catch { }

            ServerCore server = new("http://localhost:23333/");
            server.RemoteClientReceive += receiver =>
            {
                receiver.ExcuteAction();
            };
            
            ServerCore = server;
            ServerCore.LaunchAsync().GetAwaiter().GetResult();
        }
        catch(Exception ex)
        {
            ex.LogToConsole();
        }

        return ServerCore;
    }


    [CommandToken("stop", "exit", "退出", "关闭", "Close", "停服")]
    public static void Stop()
    {
        foreach(var remote_client in ServerCore.RemoteSessions)
        {
            var ip = remote_client.RequestUri;
            remote_client.CloseAsync();

            if (ip != null) $"远程客户端 [{ip}] 已关闭".LogToConsole();
        }

        ServerCore.Close();
        Environment.Exit(0);
    }




    [CommandToken("accounts", "账户列表")]
    public static void Account()
    {
        StringBuilder sb = new();

        var count = AccountManager.LoginAccountSession.Count();
        sb.AppendLine($"{count} 个用户在线");

        foreach (var i in AccountManager.LoginAccountSession)
        {
            sb.AppendLine(i.AccountToken.Value);
        }

        sb.ToString().LogToConsole();
    }


    [CommandToken("clients", "客户端列表")]
    public static void Clients()
    {
        StringBuilder sb = new();

        var count = ServerCore.RemoteSessions.Count();
        sb.AppendLine($"{count} 个客户端在线");

        foreach (var remote_client in ServerCore.RemoteSessions)
        {
            sb.AppendLine($"[ {remote_client.RequestUri} ]");
        }

        sb.ToString().LogToConsole();
    }

    #endregion
}
